document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('withdraw');
  
  // Set up variables
  let selectedCardId = null;
  let selectedCardInfo = null;
  let availableBalance = 0;
  
  // Load account balance
  loadAccountBalance();
  
  // Load bank cards
  loadBankCards();
  
  // Load withdraw history
  loadWithdrawHistory();
  
  // Set up event listeners
  document.getElementById('withdraw-all').addEventListener('click', function() {
    document.getElementById('amount-input').value = parseFloat(availableBalance).toFixed(2);
  });
  
  // Quick amount options
  const quickAmountOptions = document.querySelectorAll('.quick-amount-option');
  quickAmountOptions.forEach(option => {
    option.addEventListener('click', function() {
      const amount = this.getAttribute('data-amount');
      
      // If amount is greater than available balance, show error
      if (parseFloat(amount) > availableBalance) {
        Toast.error("余额不足");
        return;
      }
      
      document.getElementById('amount-input').value = amount;
      
      // Remove selected class from all options
      quickAmountOptions.forEach(opt => opt.classList.remove('selected'));
      
      // Add selected class to clicked option
      this.classList.add('selected');
    });
  });
  
  // Submit button
  document.getElementById('submit-btn').addEventListener('click', function() {
    validateAndSubmit();
  });
  
  // Modal close button
  document.querySelector('.modal-close').addEventListener('click', function() {
    hideModal();
  });
  
  // Cancel button
  document.getElementById('cancel-btn').addEventListener('click', function() {
    hideModal();
  });
  
  // Confirm button
  document.getElementById('confirm-btn').addEventListener('click', function() {
    submitWithdraw();
  });
  
  /**
   * Load account balance
   */
  function loadAccountBalance() {
    ApiService.get('/api/account/balance')
      .then(response => {
        if (response.code === 0 && response.data) {
          const balanceData = response.data;
          availableBalance = balanceData.availableBalance;
          document.getElementById('available-balance').textContent = Utils.formatMoney(availableBalance);
        }
      })
      .catch(error => {
        console.error('Error loading balance:', error);
        Toast.error('加载余额失败，请刷新页面重试');
      });
  }
  
  /**
   * Load bank cards
   */
  function loadBankCards() {
    const bankCardListElement = document.getElementById('bank-card-list');
    
    ApiService.get('/api/bankcard/list')
      .then(response => {
        if (response.code === 0 && response.data) {
          const cards = response.data;
          
          if (cards.length === 0) {
            bankCardListElement.innerHTML = `
              <div class="empty-state">
                <p>您还没有添加银行卡</p>
                <a href="/bankcards.html" class="btn btn-outline btn-sm mt-2">添加银行卡</a>
              </div>
            `;
            return;
          }
          
          let html = '';
          cards.forEach(card => {
            const isDefault = card.isDefault === 1;
            const bankClass = getBankClass(card.bankName);
            
            html += `
              <div class="bank-card-item ${isDefault ? 'selected' : ''}" data-id="${card.id}">
                <div class="bank-card-radio">
                  <input type="radio" name="bank-card" id="card-${card.id}" ${isDefault ? 'checked' : ''}>
                </div>
                <div class="bank-logo ${bankClass}">
                  ${getBankShortName(card.bankName)}
                </div>
                <div class="bank-card-info">
                  <div class="bank-name">${card.bankName}${card.cardType === 1 ? ' 储蓄卡' : ' 信用卡'}</div>
                  <div class="bank-card-number">${card.cardNumber}</div>
                </div>
              </div>
            `;
            
            // Set default card as selected
            if (isDefault) {
              selectedCardId = card.id;
              selectedCardInfo = card;
            }
          });
          
          bankCardListElement.innerHTML = html;
          
          // Add click event to select bank card
          const bankCardItems = document.querySelectorAll('.bank-card-item');
          bankCardItems.forEach(item => {
            item.addEventListener('click', function() {
              const id = this.getAttribute('data-id');
              
              // Remove selected class from all items
              bankCardItems.forEach(i => i.classList.remove('selected'));
              
              // Add selected class to clicked item
              this.classList.add('selected');
              
              // Check the radio button
              this.querySelector('input[type="radio"]').checked = true;
              
              // Update selected card id
              selectedCardId = id;
              
              // Update selected card info
              selectedCardInfo = cards.find(card => card.id == id);
            });
          });
        }
      })
      .catch(error => {
        console.error('Error loading bank cards:', error);
        bankCardListElement.innerHTML = `
          <div class="empty-state">
            <p>加载银行卡失败，请刷新页面重试</p>
          </div>
        `;
      });
  }
  
  /**
   * Get bank class for styling
   */
  function getBankClass(bankName) {
    if (bankName.includes('工商')) return 'icbc';
    if (bankName.includes('农业')) return 'abc';
    if (bankName.includes('中国银行')) return 'boc';
    if (bankName.includes('建设')) return 'ccb';
    return '';
  }
  
  /**
   * Get bank short name
   */
  function getBankShortName(bankName) {
    if (bankName.includes('工商')) return 'ICBC';
    if (bankName.includes('农业')) return 'ABC';
    if (bankName.includes('中国银行')) return 'BOC';
    if (bankName.includes('建设')) return 'CCB';
    return bankName.substring(0, 2);
  }
  
  /**
   * Load withdraw history
   */
  function loadWithdrawHistory() {
    const historyListElement = document.getElementById('withdraw-history-list');
    
    ApiService.get('/api/transaction/list', { tradeType: 2, page: 1, size: 5 })
      .then(response => {
        if (response.code === 0 && response.data) {
          const transactions = response.data.list || [];
          
          if (transactions.length === 0) {
            historyListElement.innerHTML = `
              <div class="empty-state">
                <p>暂无提现记录</p>
              </div>
            `;
            return;
          }
          
          let html = '';
          transactions.forEach(transaction => {
            const statusClass = getStatusClass(transaction.status);
            const statusText = getStatusText(transaction.status);
            
            html += `
              <div class="history-item">
                <div class="history-info">
                  <div>提现</div>
                  <div class="history-date">${Utils.formatDate(transaction.createTime, true)}</div>
                </div>
                <div class="history-amount">¥${transaction.amount.toFixed(2)}</div>
                <div class="history-status ${statusClass}">${statusText}</div>
              </div>
            `;
          });
          
          historyListElement.innerHTML = html;
        }
      })
      .catch(error => {
        console.error('Error loading withdraw history:', error);
        historyListElement.innerHTML = `
          <div class="empty-state">
            <p>加载提现记录失败，请刷新页面重试</p>
          </div>
        `;
      });
  }
  
  /**
   * Get status class for styling
   */
  function getStatusClass(status) {
    switch (status) {
      case 1: return 'success';
      case 0: return 'pending';
      case 2: return 'failed';
      default: return '';
    }
  }
  
  /**
   * Get status text
   */
  function getStatusText(status) {
    switch (status) {
      case 1: return '成功';
      case 0: return '处理中';
      case 2: return '失败';
      default: return '未知';
    }
  }
  
  /**
   * Validate inputs and show confirmation modal
   */
  function validateAndSubmit() {
    // Validate bank card
    if (!selectedCardId) {
      Toast.error('请选择银行卡');
      return;
    }
    
    // Validate amount
    const amountInput = document.getElementById('amount-input');
    const amount = parseFloat(amountInput.value);
    
    if (isNaN(amount) || amount <= 0) {
      Toast.error('请输入有效的提现金额');
      amountInput.focus();
      return;
    }
    
    if (amount < 100) {
      Toast.error('提现金额不能低于100元');
      amountInput.focus();
      return;
    }
    
    if (amount > 50000) {
      Toast.error('单笔提现金额不能超过50000元');
      amountInput.focus();
      return;
    }
    
    if (amount > availableBalance) {
      Toast.error('余额不足');
      amountInput.focus();
      return;
    }
    
    // Validate password
    const passwordInput = document.getElementById('password');
    if (!passwordInput.value) {
      Toast.error('请输入安全密码');
      passwordInput.focus();
      return;
    }
    
    // Show confirmation modal
    showConfirmationModal(amount);
  }
  
  /**
   * Show confirmation modal
   */
  function showConfirmationModal(amount) {
    // Update confirmation details
    document.getElementById('confirm-amount').textContent = Utils.formatMoney(amount);
    document.getElementById('confirm-actual-amount').textContent = Utils.formatMoney(amount);
    
    if (selectedCardInfo) {
      const cardInfo = `${selectedCardInfo.bankName} (${selectedCardInfo.cardNumber})`;
      document.getElementById('confirm-bank-card').textContent = cardInfo;
    }
    
    // Show modal
    const modal = document.getElementById('confirmation-modal');
    modal.style.display = 'flex';
  }
  
  /**
   * Hide modal
   */
  function hideModal() {
    const modal = document.getElementById('confirmation-modal');
    modal.style.display = 'none';
  }
  
  /**
   * Submit withdraw request
   */
  function submitWithdraw() {
    const amount = parseFloat(document.getElementById('amount-input').value);
    const password = document.getElementById('password').value;
    
    // Disable confirm button to prevent double submission
    const confirmBtn = document.getElementById('confirm-btn');
    confirmBtn.disabled = true;
    confirmBtn.innerText = '处理中...';
    
    // Prepare request data
    const requestData = {
      amount: amount,
      bankCardId: selectedCardId,
      password: password
    };
    
    // Call API
    ApiService.post('/api/account/withdraw', requestData)
      .then(response => {
        if (response.code === 0) {
          // Hide modal
          hideModal();
          
          // Show success message
          Toast.success('提现申请已提交，请等待处理');
          
          // Reset form
          document.getElementById('amount-input').value = '';
          document.getElementById('password').value = '';
          
          // Reload balance and history
          loadAccountBalance();
          loadWithdrawHistory();
        } else {
          Toast.error(response.message || '提现失败，请稍后再试');
        }
      })
      .catch(error => {
        console.error('Error submitting withdraw:', error);
        Toast.error('系统错误，请稍后再试');
      })
      .finally(() => {
        // Re-enable confirm button
        confirmBtn.disabled = false;
        confirmBtn.innerText = '确认提现';
      });
  }
});
